<?php

class CustomFieldOption extends AppModel
{
	var $name = "CustomFieldOption";
	
	var $displayField = "field_value";
	
	var $fieldProperties = array(
			"field_value" => array(
					"label"=>"Option",
					"type"=>"text",
					'group'=>array('add')
			)
	);

	var $validate = array(
			"field_value" => array(
					"rule" => VALID_NOT_EMPTY,
					"message" => "This field is required"
			)
	);

	var $belongsTo = array(
			'CustomField'=>array(
					'className' => 'CustomField',
					'foreignKey' => 'custom_field_id',
					'dependent' => true,
					'conditions' => '',
					'fields' => '',
					'order' => array('CustomFieldOption.sort_order'=>'ASC')
			)
	);

	var $order = array('CustomFieldOption.sort_order'=>'ASC');

	function getFieldOptionsList($customFieldId)
	{
		return $this->find('list',array('conditions'=>array('custom_field_id' => $customFieldId),'fields'=>array('key','field_value'),'order'=>array('sort_order'=>'ASC'),'recursive'=>-1));
	}
	
	function beforeChildrenSave($data)
	{
		$i = 1;
		foreach($data as $key => $value)
		{
			if(!@$data[$key]['id'])
			{
				unset($data[$key]['id']);
			}
			$data[$key]['sort_order'] = $i++;
		}
		return $data;
	}
	function beforeSave($options = array()) 
	{
		if($this->_isNew())
		{
			if(!isset($this->data[$this->alias]['key']))
			{
				$key = $this->field("id",array(),"id desc");
				if(!$key)
				{
					$key = 1;
				}
				$key++;
				$this->data[$this->alias]['key'] = $key;
			}
			if(!isset($this->data[$this->alias]['sort_order']))
			{
				$this->data[$this->alias]['sort_order'] = $key;
			}
		}
		return parent::beforeSave($options);
	}

}
?>